// 1. 枚举定义
export const CoupleMode = Object.freeze({
  COUPLE_AC: 0,
  COUPLE_DC: 1,
});

export const GainMode = Object.freeze({
  GAIN_X1: 0,
  GAIN_X10: 1,
  GAIN_X100: 2,
});

export const InputMode = Object.freeze({
  INPUT_5V: 0,
  INPUT_12V: 1,
  INPUT_24V: 2,
  INPUT_ICP: 3,
  INPUT_NO_EXTERNAL_EXCITATION: 4,
  INPUT_FULL_BRIDGE: 5,
  INPUT_HALF_BRIDGE: 6,
  INPUT_QUARTER_BRIDGE: 7,
});

// 2. 打包函数
// 返回 { ok: Boolean, p0: Number, p1: Number }
export function encodeFrontEndConfig(cm, gm, im) {
  // 合法性检查
  if (im === InputMode.INPUT_ICP && cm !== CoupleMode.COUPLE_AC) {
    return { ok: false, p0: 0, p1: 0 };
  }
  if (
    (im === InputMode.INPUT_FULL_BRIDGE ||
      im === InputMode.INPUT_HALF_BRIDGE ||
      im === InputMode.INPUT_QUARTER_BRIDGE) &&
    cm !== CoupleMode.COUPLE_DC
  ) {
    return { ok: false, p0: 0, p1: 0 };
  }

  let p0 = 0;
  let p1 = 0;

  // CoupleMode
  if (cm === CoupleMode.COUPLE_DC) p0 |= 0x20;

  // GainMode
  if (gm === GainMode.GAIN_X10) p0 |= 0x01;
  else if (gm === GainMode.GAIN_X100) p0 |= 0x02;

  // InputMode
  switch (im) {
    case InputMode.INPUT_5V:
      p0 |= 0xc0;
      p1 |= 0x40;
      break;
    case InputMode.INPUT_12V:
      p0 |= 0xc0;
      p1 |= 0x80;
      break;
    case InputMode.INPUT_24V:
      p0 |= 0xc0;
      p1 |= 0xc0;
      break;
    case InputMode.INPUT_ICP:
      p0 |= 0x40;
      p1 |= 0xc0;
      break;
    case InputMode.INPUT_NO_EXTERNAL_EXCITATION:
      p0 |= 0xc0;
      p1 |= 0x60;
      break;
    case InputMode.INPUT_FULL_BRIDGE:
      p0 |= 0xc0;
      p1 |= 0x10;
      break;
    case InputMode.INPUT_HALF_BRIDGE:
      p0 |= 0x80;
      p1 |= 0x10;
      break;
    case InputMode.INPUT_QUARTER_BRIDGE:
      p0 |= 0x80;
      break;
  }
  return { ok: true, p0, p1 };
}

export function encodeFrontEndConfigBytes(
  cm,
  gm,
  im,
  target = new Uint8Array(2)
) {
  const { ok, p0, p1 } = encodeFrontEndConfig(cm, gm, im);
  if (ok) {
    target[0] = p0;
    target[1] = p1;
  }
  return ok ? target : null;
}
